package com.lingqi;

import com.lingqi.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

// 有事务，主动失败
public class Demo5 {
    public static void main(String[] args) throws SQLException {
        String sql1 = "insert into records (rid, bid) values (1, 2)";
        String sql2 = "update books set count = count - 1 where bid = 2";

        // 要使用事务，在同一个事务中，操作 sql1 和 sql2，意味着必须在一条 Connection 完成
        try(Connection c = DBUtil.connection()){
            c.setAutoCommit(false);

            try(PreparedStatement ps = c.prepareStatement(sql1)){
                ps.executeUpdate();
            }

            try(PreparedStatement ps = c.prepareStatement(sql2)){
                ps.executeUpdate();
            }

            c.rollback();   //主动失败
        }
    }
}
